#include "stdio.h"
#include "nvs_flash.h"
#include "esp_log.h"
#include "driver/gpio.h"
#include "driver/i2c_master.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/queue.h"
#include "esp_wifi.h"
#include "esp_event.h"
#include "esp_task_wdt.h"
#include "esp_timer.h"
#include "esp_bt.h"
#include "esp_bt_main.h"
#include "esp_a2dp_api.h"
#include "esp_bt_device.h"
#include "esp_gap_bt_api.h"
#include "driver/i2s_std.h"
#include "esp_avrc_api.h"

#include "ssd1306.h"
// #include "wifi.h"
#include "timer.h"
#include "dsl_button.h"

#define I2S_BCK GPIO_NUM_27
#define I2S_WS GPIO_NUM_25
#define I2S_DOUT GPIO_NUM_26

#define PCM_XSMT GPIO_NUM_32
#define PCM_FMT GPIO_NUM_33
#define PCM_FLT GPIO_NUM_12
#define PCM_DEMP GPIO_NUM_13
#define GF_8002A_SD GPIO_NUM_23

#define SAMPLE_RATE 44100
#define FREQ 440

#define BUFFER_SIZE 1024

// 初始化 I2C 总线
static volatile i2c_master_bus_handle_t bus_handle;

void i2c_master_bus_init(void);
static bool IRAM_ATTR timer_isr_callback(gptimer_handle_t timer,
                                         const gptimer_alarm_event_data_t *edata,
                                         void *user_data);

void vOledTaskCode(void *pvParameters);
void vWifiConnectTaskCode(void *pvParameters);
void vBtTaskCode(void *pvParameters);
void vMainTaskCode(void *pvParameters);
void vKeyTaskCode(void *pvParameters);

static uint8_t led_flag = 0;
static i2s_chan_handle_t tx_handle;

static uint8_t play_status = 0;
static uint8_t avrc_connected = 0;
static uint8_t current_volume = 0;

void app_main(void)
{
    esp_task_wdt_config_t wdt_config = {
        .timeout_ms = 10000,
        .idle_core_mask = 0,
        .trigger_panic = true,
    };
    esp_task_wdt_init(&wdt_config); // 设置为 10 秒内必须喂狗

    esp_err_t ret;

    // 初始化 NVS
    ret = nvs_flash_init();
    if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND)
    {
        // NVS 分区被截断，需要擦除
        ESP_ERROR_CHECK(nvs_flash_erase());
        ret = nvs_flash_init();
    }
    ESP_ERROR_CHECK(ret);

    // 初始化默认事件循环
    ret = esp_event_loop_create_default();
    ESP_ERROR_CHECK(ret);

    // 初始化 esp-netif
    esp_netif_init();

    // 创建默认的 STA 网络接口
    esp_netif_create_default_wifi_sta();

    // 初始化 i2c 总线
    i2c_master_bus_init();

    // 初始化定时器
    timer_init(timer_isr_callback);

    // 初始化按键
    dsl_button_init();

    xTaskCreate(vOledTaskCode, "vOledTaskCode", 4096, NULL, 5, NULL);
    xTaskCreate(vMainTaskCode, "vMainTaskCode", 2048, NULL, 5, NULL);
    xTaskCreate(vBtTaskCode, "vBtTaskCode", 4096, NULL, 5, NULL);
}

void i2c_master_bus_init(void)
{
    i2c_master_bus_config_t bus_config = {
        .sda_io_num = 21,
        .scl_io_num = 22,
        .flags = {
            .enable_internal_pullup = true},
        .clk_source = I2C_CLK_SRC_DEFAULT,
        .i2c_port = I2C_NUM_0,
    };
    esp_err_t ret = i2c_new_master_bus(&bus_config, &bus_handle);
    if (ret == ESP_OK)
    {
        ESP_LOGI("I2C", "I2C bus created successfully");
    }
    else
    {
        ESP_LOGE("I2C", "I2C bus creation failed");
    }
}

static bool IRAM_ATTR timer_isr_callback(gptimer_handle_t timer,
                                         const gptimer_alarm_event_data_t *edata,
                                         void *user_data)
{
    dsl_button_tick();
    return false; // 返回false表示不需要唤醒高优先级任务
}

void vOledTaskCode(void *pvParameters)
{
    ssd1306_init_with_bus(bus_handle);
    ssd1306_clear();
    // ssd1306_draw_hline(10, 50, 0);

    // ssd1306_draw_rect(20, 20, 100, 30);

    // ssd1306_reverse(1);

    // ssd1306_write_char('a', 30, 50, 16);
    // ssd1306_write_char('b', 40, 50, 16);
    // ssd1306_write_char('A', 50, 50, 16);

    ssd1306_write_chinese(0, 40, 32, 16);
    ssd1306_write_chinese(1, 60, 32, 16);
    ssd1306_write_chinese(13, 80, 32, 16);
    // ssd1306_write_chinese(1, 40, 50, 16);
    // ssd1306_write_chinese(13, 60, 50, 16);

    ssd1306_update();

    esp_task_wdt_add(NULL);

    while (1)
    {
        esp_task_wdt_reset();
        vTaskDelay(pdMS_TO_TICKS(1000));
    }

    esp_task_wdt_delete(NULL);
}

void vWifiConnectTaskCode(void *pvParameters)
{

    esp_task_wdt_add(NULL);
    while (1)
    {
        esp_task_wdt_reset();
        vTaskDelay(pdMS_TO_TICKS(1000));
    }
    esp_task_wdt_delete(NULL);
}

void vMainTaskCode(void *pvParameters)
{
    static uint8_t led_status = 0;

    esp_task_wdt_add(NULL);
    gpio_set_direction(GPIO_NUM_25, GPIO_MODE_OUTPUT);
    while (1)
    {
        if (led_flag == 1)
        {
            gpio_set_level(GPIO_NUM_25, led_status);
            led_flag = 0;
            led_status ^= 1;
        }

        vTaskDelay(pdMS_TO_TICKS(10));

        esp_task_wdt_reset();
    }
}

void bt_dev_cb(esp_bt_dev_cb_event_t event, esp_bt_dev_cb_param_t *param)
{
    ESP_LOGI("BT-DEV", "bt_dev_cb event: %d, param: %p", event, param);
    if (event == ESP_BT_DEV_NAME_RES_EVT)
    {
        ESP_LOGI("BT-DEV", "name: %s", param->name_res.name);
    }
}

void bt_gap_cb(esp_bt_gap_cb_event_t event, esp_bt_gap_cb_param_t *param)
{
    ESP_LOGI("BT-GAP", "esp_bt_gap_cb_event_t: %d", event);
    

    switch (event)
    {
    case ESP_BT_GAP_AUTH_CMPL_EVT:
        ESP_LOGI("BT-GAP", "认证完成: %d", param->auth_cmpl.stat);
        if(param->auth_cmpl.stat == ESP_BT_STATUS_SUCCESS)
        {
            ESP_LOGI("BT-GAP", "认证成功 mac: " ESP_BD_ADDR_STR, ESP_BD_ADDR_HEX(param->auth_cmpl.bda));
            nvs_handle_t bt_nvs_handle;
            nvs_open("bt", NVS_READWRITE, &bt_nvs_handle);
            nvs_set_blob(bt_nvs_handle, "remote_bda", param->auth_cmpl.bda, 6);
            nvs_commit(bt_nvs_handle);
            nvs_close(bt_nvs_handle);
        }
        break;
    case ESP_BT_GAP_DISC_RES_EVT:
        ESP_LOGI("BT-GAP", "发现设备: %d", param->disc_res.num_prop);
        break;
    case ESP_BT_GAP_DISC_STATE_CHANGED_EVT:
        ESP_LOGI("BT-GAP", "发现状态改变");
        break;
    case ESP_BT_GAP_GET_DEV_NAME_CMPL_EVT:
        ESP_LOGI("BT-GAP", "获取设备名称完成: %s", param->get_dev_name_cmpl.name);
        break;
    default:
        break;
    }
}

void avrc_tg_callback(esp_avrc_tg_cb_event_t event, esp_avrc_tg_cb_param_t *param)
{
    switch (event)
    {
    case ESP_AVRC_TG_REMOTE_FEATURES_EVT:

        break;
    default:
        break;
    }
}

void avrc_ct_callback(esp_avrc_ct_cb_event_t event, esp_avrc_ct_cb_param_t *param)
{
    switch (event)
    {
    case ESP_AVRC_CT_CONNECTION_STATE_EVT:
        if (param->conn_stat.connected)
        {
            ESP_LOGI("AVRC CT", "AVRC 连接成功");
            avrc_connected = 1;
        }
        else
        {
            ESP_LOGI("AVRC CT", "AVRC 断开");
            avrc_connected = 0;
        }
        break;
    case ESP_AVRC_CT_REMOTE_FEATURES_EVT:
        uint32_t features = param->rmt_feats.feat_mask;
        ESP_LOGI("AVRC CT", "Remote device features");

        // 检查是否支持绝对音量
        bool support_abs_volume = features & ESP_AVRC_FEAT_ADV_CTRL;
        ESP_LOGI("AVRC CT", "Supports absolute volume: %s", support_abs_volume ? "YES" : "NO");
        break;

    case ESP_AVRC_CT_PASSTHROUGH_RSP_EVT:
        ESP_LOGI("AVRC CT", "收到 AVRC 响应: %d", param->psth_rsp.rsp_code);
        ESP_LOGI("AVRC CT", "收到 AVRC 按键: %d", param->psth_rsp.key_code);
        break;
    case ESP_AVRC_CT_SET_ABSOLUTE_VOLUME_RSP_EVT:
        // 处理绝对音量响应
        current_volume = param->set_volume_rsp.volume;
        ESP_LOGI("AVRC CT", "Absolute volume set to: %d (%.1f%%)",
                 current_volume, (current_volume * 100.0) / 127.0);
        break;
    default:
        break;
    }
}

void a2d_callback(esp_a2d_cb_event_t event, esp_a2d_cb_param_t *param)
{
    ESP_LOGI("A2DP CALLBACK", "a2d_cb event: %d, param: %p", event, param);
    switch (event)
    {
    case ESP_A2D_CONNECTION_STATE_EVT:
        if (param->conn_stat.state == ESP_A2D_CONNECTION_STATE_CONNECTED)
        {
            // 连接成功后自动开始播放
            // 注意：某些设备可能需要等待音频流建立
            ESP_LOGI("A2DP CALLBACK", "a2d_connection_cb connected");
        }
        break;
    case ESP_A2D_AUDIO_STATE_EVT:
        // 处理音频状态变化（如开始、暂停）
        ESP_LOGI("A2DP CALLBACK", "a2d_data_cb state: %d", param->audio_stat.state);
        play_status = param->audio_stat.state;
        break;
    default:
        break;
    }
}

void a2d_data_callback(const uint8_t *buf, uint32_t len)
{
    ESP_LOGI("A2DP DATA CALLBACK", "a2d_data_cb len");
    size_t bytes_written;
    i2s_channel_write(tx_handle, buf, len, &bytes_written, pdMS_TO_TICKS(1000));
}


void vBtTaskCode(void *pvParameters)
{
    esp_err_t ret;

    esp_bt_controller_config_t bt_cfg = BT_CONTROLLER_INIT_CONFIG_DEFAULT(); // 初始化蓝牙控制器
    ret = esp_bt_controller_init(&bt_cfg);                                   // 初始化蓝牙控制器
    if (ret == ESP_OK)
    {
        ESP_LOGI("BT", "esp_bt_controller_init success");
    }
    else
    {
        ESP_LOGE("BT", "esp_bt_controller_init failed, err: %s", esp_err_to_name(ret));
    }

    ret = esp_bt_controller_enable(ESP_BT_MODE_BTDM); // 启动蓝牙控制器
    ESP_ERROR_CHECK(ret);
    if (ret == ESP_OK)
    {
        ESP_LOGI("BT", "esp_bt_controller_enable success");
    }
    else
    {
        ESP_LOGE("BT", "esp_bt_controller_enable failed, err: %s", esp_err_to_name(ret));
    }

    uint8_t retry_times = 0;
    while (esp_bt_controller_get_status() != ESP_BT_CONTROLLER_STATUS_ENABLED)
    {
        ESP_LOGI("BT", "esp_bt_controller_get_status times: %d", retry_times);
        if (retry_times > 100)
        {
            ESP_LOGI("BT", "esp_bt_controller_get_status failed, TIMEOUT");
            break;
        }
        retry_times++;
        vTaskDelay(pdMS_TO_TICKS(100));
    }

    ret = esp_bluedroid_init(); // 初始化蓝牙协议栈
    if (ret == ESP_OK)
    {
        ESP_LOGI("BT", "esp_bluedroid_init success");
    }
    else
    {
        ESP_LOGE("BT", "esp_bluedroid_init failed, err: %s", esp_err_to_name(ret));
    }

    ret = esp_bluedroid_enable(); // 启用蓝牙协议栈
    if (ret == ESP_OK)
    {
        ESP_LOGI("BT", "esp_bluedroid_enable success");
    }
    else
    {
        ESP_LOGE("BT", "esp_bluedroid_enable failed, err: %s", esp_err_to_name(ret));
    }

    ret = esp_bt_gap_set_device_name("ESP32-Test"); // 设置蓝牙设备名称

    if (ret == ESP_OK)
    {
        ESP_LOGI("BT", "esp_bt_dev_set_device_name success");
    }
    else
    {
        ESP_LOGE("BT", "esp_bt_dev_set_device_name failed, err: %s", esp_err_to_name(ret));
    }

    ret = esp_bt_dev_register_callback(bt_dev_cb); // 注册蓝牙回调函数
    if (ret == ESP_OK)
    {
        ESP_LOGI("BT", "esp_bt_dev_register_callback success");
    }
    else
    {
        ESP_LOGE("BT", "esp_bt_dev_register_callback failed, err: %s", esp_err_to_name(ret));
    }

    ret = esp_bt_gap_register_callback(bt_gap_cb); // 注册蓝牙gap回调函数
    if (ret == ESP_OK)
    {
        ESP_LOGI("BT", "esp_bt_gap_register_callback success");
    }
    else
    {
        ESP_LOGE("BT", "esp_bt_gap_register_callback failed, err: %s", esp_err_to_name(ret));
    }

    ret = esp_bt_gap_set_scan_mode(ESP_BT_CONNECTABLE, ESP_BT_GENERAL_DISCOVERABLE); // 设置蓝牙可见性
    if (ret == ESP_OK)
    {
        ESP_LOGI("BT", "esp_bt_gap_set_scan_mode success");
    }
    else
    {
        ESP_LOGE("BT", "esp_bt_gap_set_scan_mode failed, err: %s", esp_err_to_name(ret));
    }
    // 初始化蓝牙 AVRCP 目标模块，此函数应在 esp_bluedroid_enable() 成功完成后调用。注意：AVRC 不能独立工作，AVRC 应与 A2DP 一起使用，并且应该在 A2DP 之前初始化 AVRC。
    // 接收远程控制命令（被控端）
    // 功能：实现蓝牙音频远程控制的被控端（如耳机接收手机控制指令）。
    // 应用场景：开发支持远程控制的音频设备，接收来自控制器的命令（播放 / 暂停 / 音量调节）。
    ret = esp_avrc_tg_init();
    if (ret == ESP_OK)
    {
        ESP_LOGI("BT", "esp_avrc_tg_init success");
    }
    else
    {
        ESP_LOGE("BT", "esp_avrc_tg_init failed, err: %s", esp_err_to_name(ret));
    }
    // 注册应用程序回调到AVRCP目标模块。此函数应在esp_bluedroid_enable()成功完成后调用。
    ret = esp_avrc_tg_register_callback(avrc_tg_callback);
    if (ret == ESP_OK)
    {
        ESP_LOGI("BT", "esp_avrc_tg_register_callback success");
    }
    else
    {
        ESP_LOGE("BT", "esp_avrc_tg_register_callback failed, err: %s", esp_err_to_name(ret));
    }
    // 初始化蓝牙 AVRCP 控制器模块，此函数应在 esp_bluedroid_enable() 成功完成后调用。注意：AVRC 不能独立工作，AVRC 应与 A2DP 一起使用，并且应先于 A2DP 初始化 AVRC。
    // 发送远程控制命令（控制端）
    ret = esp_avrc_ct_init();
    if (ret == ESP_OK)
    {
        ESP_LOGI("BT", "esp_avrc_ct_init success");
    }
    else
    {
        ESP_LOGE("BT", "esp_avrc_ct_init failed, err: %s", esp_err_to_name(ret));
    }
    // 注册应用回调到AVRCP模块。此函数应在esp_bluedroid_enable()成功完成后调用。
    ret = esp_avrc_ct_register_callback(avrc_ct_callback);
    if (ret == ESP_OK)
    {
        ESP_LOGI("BT", "esp_avrc_ct_register_callback success");
    }
    else
    {
        ESP_LOGE("BT", "esp_avrc_ct_register_callback failed, err: %s", esp_err_to_name(ret));
    }

    ret = esp_a2d_sink_init(); // 初始化蓝牙音频
    if (ret == ESP_OK)
    {
        ESP_LOGI("BT", "esp_a2d_sink_init success");
    }
    else
    {
        ESP_LOGE("BT", "esp_a2d_sink_init failed, err: %s", esp_err_to_name(ret));
    }
    ret = esp_a2d_register_callback(a2d_callback); // 注册蓝牙音频回调函数
    if (ret == ESP_OK)
    {
        ESP_LOGI("BT", "esp_a2d_register_callback success");
    }
    else
    {
        ESP_LOGE("BT", "esp_a2d_register_callback failed, err: %s", esp_err_to_name(ret));
    }

    ret = esp_a2d_sink_register_data_callback(a2d_data_callback); // 注册蓝牙音频数据回调函数
    if (ret == ESP_OK)
    {
        ESP_LOGI("BT", "esp_a2d_sink_register_data_callback success");
    }
    else
    {
        ESP_LOGE("BT", "esp_a2d_sink_register_data_callback failed, err: %s", esp_err_to_name(ret));
    }

    // 通过读取保存的蓝牙地址，连接蓝牙设备
    nvs_handle_t nvs_handle;
    nvs_open("bt", NVS_READWRITE, &nvs_handle);
    ret = nvs_find_key(nvs_handle, "remote_bda", NULL);
    if(ret == ESP_OK) {
        esp_bd_addr_t remote_bda;
        size_t size = sizeof(remote_bda);
        ESP_LOGI("BT-NVS", "size = %d", size);
        ret = nvs_get_blob(nvs_handle, "remote_bda", remote_bda, &size);
        if(ret == ESP_OK && size == sizeof(remote_bda))
        {
            ESP_LOGI("BT-NVS", "Found remote_bda in NVS");
            ESP_LOGI("BT-NVS", "remote_bda: " ESP_BD_ADDR_STR, ESP_BD_ADDR_HEX(remote_bda));
            esp_a2d_sink_connect(remote_bda);
        } else {
            ESP_LOGE("BT-NVS", "Error (%s) reading BLOB or invalid length", esp_err_to_name(ret));
        }
    }
    nvs_close(nvs_handle);

    // 处理 PCM5102A 相关
    gpio_set_direction(PCM_XSMT, GPIO_MODE_OUTPUT);
    gpio_set_direction(PCM_FMT, GPIO_MODE_OUTPUT);
    gpio_set_direction(PCM_FLT, GPIO_MODE_OUTPUT);
    gpio_set_direction(PCM_DEMP, GPIO_MODE_OUTPUT);
    gpio_set_direction(GF_8002A_SD, GPIO_MODE_OUTPUT);

    gpio_set_level(PCM_XSMT, 1);
    gpio_set_level(PCM_FMT, 0);
    gpio_set_level(PCM_FLT, 0);
    gpio_set_level(PCM_DEMP, 0);
    gpio_set_level(GF_8002A_SD, 0);

    i2s_chan_config_t chan_cfg = I2S_CHANNEL_DEFAULT_CONFIG(I2S_NUM_0, I2S_ROLE_MASTER);
    ret = i2s_new_channel(&chan_cfg, &tx_handle, NULL);
    if (ret == ESP_OK)
    {
        ESP_LOGI("I2S_INIT", "I2S initialized successfully");
    }
    else
    {
        ESP_LOGE("I2S_INIT", "Failed to initialize I2S: %s", esp_err_to_name(ret));
    }
    i2s_std_config_t std_config = {
        .clk_cfg = I2S_STD_CLK_DEFAULT_CONFIG(44100),
        .slot_cfg = I2S_STD_PHILIPS_SLOT_DEFAULT_CONFIG(I2S_DATA_BIT_WIDTH_16BIT, I2S_SLOT_MODE_STEREO),
        .gpio_cfg = {
            .mclk = I2S_GPIO_UNUSED,
            .bclk = I2S_BCK,
            .ws = I2S_WS,
            .din = I2S_GPIO_UNUSED,
            .dout = I2S_DOUT,
            .invert_flags = {
                .bclk_inv = false,
                .ws_inv = false,
                .mclk_inv = false,
            },
        },
    };
    ret = i2s_channel_init_std_mode(tx_handle, &std_config);
    if (ret == ESP_OK)
    {
        ESP_LOGI("I2S_INIT", "I2S std mode initialized successfully");
    }
    else
    {
        ESP_LOGE("I2S_INIT", "Failed to initialize I2S: %s", esp_err_to_name(ret));
    }

    ret = i2s_channel_enable(tx_handle);
    if (ret == ESP_OK)
    {
        ESP_LOGI("I2S_INIT", "I2S enabled successfully");
    }
    else
    {
        ESP_LOGE("I2S_INIT", "Failed to enable I2S: %s", esp_err_to_name(ret));
    }

    esp_task_wdt_add(NULL);

    static uint8_t tl = 0;

    while (1)
    {

        if (dsl_button_check(BUTTON_TYPE_OK, DSL_BUTTON_EVENT_CLICK))
        {
            play_status = !play_status;

            ESP_LOGI("BT", "BUTTON_TYPE_OK DSL_BUTTON_EVENT_CLICK");
            // 播放和暂停音乐
            esp_avrc_ct_send_passthrough_cmd(++tl, play_status ? ESP_AVRC_PT_CMD_PLAY : ESP_AVRC_PT_CMD_PAUSE, ESP_AVRC_PT_CMD_STATE_PRESSED);
            vTaskDelay(pdMS_TO_TICKS(100));
            tl = tl > 15 ? 0 : tl;
            esp_avrc_ct_send_passthrough_cmd(++tl, play_status ? ESP_AVRC_PT_CMD_PLAY : ESP_AVRC_PT_CMD_PAUSE, ESP_AVRC_PT_CMD_STATE_RELEASED);
        }

        if (dsl_button_check(BUTTON_TYPE_LEFT, DSL_BUTTON_EVENT_CLICK))
        {
            ESP_LOGI("BT", "BUTTON_TYPE_LEFT DSL_BUTTON_EVENT_CLICK");
            esp_avrc_ct_send_passthrough_cmd(++tl, ESP_AVRC_PT_CMD_BACKWARD, ESP_AVRC_PT_CMD_STATE_PRESSED);
            vTaskDelay(pdMS_TO_TICKS(100));
            tl = tl > 15 ? 0 : tl;
            esp_avrc_ct_send_passthrough_cmd(++tl, ESP_AVRC_PT_CMD_BACKWARD, ESP_AVRC_PT_CMD_STATE_RELEASED);
        }

        if (dsl_button_check(BUTTON_TYPE_RIGHT, DSL_BUTTON_EVENT_CLICK))
        {
            ESP_LOGI("BT", "BUTTON_TYPE_RIGHT DSL_BUTTON_EVENT_CLICK");
            esp_avrc_ct_send_passthrough_cmd(++tl, ESP_AVRC_PT_CMD_FORWARD, ESP_AVRC_PT_CMD_STATE_PRESSED);
            vTaskDelay(pdMS_TO_TICKS(100));
            tl = tl > 15 ? 0 : tl;
            esp_avrc_ct_send_passthrough_cmd(++tl, ESP_AVRC_PT_CMD_FORWARD, ESP_AVRC_PT_CMD_STATE_RELEASED);
        }

        if (dsl_button_check(BUTTON_TYPE_UP, DSL_BUTTON_EVENT_REPEAT))
        {
            ESP_LOGI("BT", "BUTTON_TYPE_UP DSL_BUTTON_EVENT_REPEAT");
            current_volume++;
            ret = esp_avrc_ct_send_set_absolute_volume_cmd(++tl, current_volume);
            if (ret == ESP_OK)
            {
                ESP_LOGI("BT", "esp_avrc_ct_send_set_absolute_volume_cmd success, volume: %d", current_volume);
            }
            else
            {
                ESP_LOGE("BT", "esp_avrc_ct_send_set_absolute_volume_cmd failed, err: %s", esp_err_to_name(ret));
            }
        }

        if (dsl_button_check(BUTTON_TYPE_DOWN, DSL_BUTTON_EVENT_REPEAT))
        {
            ESP_LOGI("BT", "BUTTON_TYPE_DOWN DSL_BUTTON_EVENT_REPEAT");
            current_volume--;
            ret = esp_avrc_ct_send_set_absolute_volume_cmd(++tl, current_volume);
            if (ret == ESP_OK)
            {
                ESP_LOGI("BT", "esp_avrc_ct_send_set_absolute_volume_cmd success volume: %d", current_volume);
            }
            else
            {
                ESP_LOGE("BT", "esp_avrc_ct_send_set_absolute_volume_cmd failed, err: %s", esp_err_to_name(ret));
            }
        }

        tl = tl > 15 ? 0 : tl;

        esp_task_wdt_reset();
        vTaskDelay(pdMS_TO_TICKS(20));
    }
}